package com.paw.ruoyi.admin.controller.common;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.util.StrUtil;
import com.paw.ruoyi.admin.common.annotion.OperatorLog;
import com.paw.ruoyi.admin.common.annotion.SkipLogParam;
import com.paw.ruoyi.admin.common.constant.BusinessType;
import com.paw.ruoyi.admin.common.domain.Result;
import com.paw.ruoyi.admin.exceptions.file.InvalidExtensionException;
import com.paw.ruoyi.admin.service.IFileUploadService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author Rubble
 * @date 2022/3/10
 **/
@RestController
public class FileUploadController {

  @Autowired
  private IFileUploadService fileUploadService;

  @SkipLogParam
  @ApiOperation("文件上传")
  @OperatorLog(title = "文件上传", businessType = BusinessType.INSERT)
  @PostMapping("/api/common/upload")
  public Result upload (@RequestParam("file") MultipartFile file) throws IOException, InvalidExtensionException {
//    String path  =  FileUploadUtils.upload(RuoYiConfig.getUploadPath(), file);
//    return Result.result(path);
    return fileUploadService.uploadFile(file);
  }

  @SkipLogParam
  @ApiOperation("批量文件上传")
  @OperatorLog(title = "批量文件上传", businessType = BusinessType.INSERT)
  @PostMapping("/api/common/uploads")
  public Result<List<String>> uploads (@RequestParam("files") MultipartFile[] files) throws IOException, InvalidExtensionException {
    List<String> paths = new ArrayList<>();
    for (MultipartFile file : files) {
//      String path  = FileUploadUtils.upload(RuoYiConfig.getUploadPath(), file);
      Result<String> result = fileUploadService.uploadFile(file);
      if(result.isSuccess() && StrUtil.isNotEmpty(result.getData())){
        paths.add(result.getData());
      }
    }

    return Result.result(paths);
  }

}
